/**
 * Copyright 2019 [shujiang.yang], Inc. All rights reserved.
 * Email: 314938230@qq.com
**/
define("pages/jbxxRsdj/jbxxRsdj_jbxx_form", [
        "../../plugins/easyui/jquery-easyui-1.5.1/jquery.easyui.min",
        "../../plugins/easyui/jquery-easyui-1.5.1/easyloader",
        '../../pages/jbxxRsdj/jbxxRsdj_form.html.js',
        "../../common/componts",
        "../../common/tools"
    ],
    function(require){
        var layerIndex;
        var _callback;
        var fileList={};
        var photosid = "";
        var formTemplate = require("./jbxxRsdj_form.html");

        /**
         * 获取表单内容
         * @param initData
         * @returns {*}
         */
        var getFormHtml = function(initData){
            var htmlCompile = template.compile(formTemplate);
            var username = CURRENT_USER.username;//获取当前办理人
            var html = htmlCompile({
                tbr:username,
                tbrq:currentDate(),
                data:initData
            });
            return html;
        };
        /**
         * 动态渲染
         */
        var parseEasyUIElement = function(){
            $.parser.parse($(".awd-form-panel"));
        };

        var _show = function(initData,callback){
            _callback = callback;
            var componts = require("../../common/componts");

            layerIndex = layer.open({
                type: 1,
                title: "数据录入",
                skin: 'layui-layer-lan', //加上边框
                closeBtn: 1, //不显示关闭按钮
                shadeClose: true, //开启遮罩关闭
                content: getFormHtml(initData),
                area:['100%','100%'],
                success: function(layero, index){
                    console.log(layero, index);
                }
            });
            layer.full(layerIndex);
            photoShwo(initData.rybh);
            setTimeout(function(){
                //初始化下拉框
                componts.initSelectPage(undefined);
                componts.initSelect(undefined,undefined,undefined);
                parseEasyUIElement(); //动态渲染
                
                
                
                $(".person-photo").change(function(){
                    var $me = $(this);
                    var id = $me.attr("id");
                    console.log('xxxxxxxxxxxxxx');
                    var file = $("#"+id)[0].files[0];
                    if (file) {
                        var img = document.getElementById(id+"Image");
                        img.onload = function(){
                            img.width  =  250;
                            img.height =  125;
                        };
                        var reader = new FileReader();
                        reader.onload = function(evt){img.src = evt.target.result;}
                        reader.readAsDataURL(file);
                    }
                })
                	
                $('#zjlxfm').textbox('setValue',initData.zjlx).combo("setText",initData.zjlxString);
                $('#xbfm').textbox('setValue',initData.xb).combo("setText",initData.xbString);
                $('#mzfm').textbox('setValue',initData.mz).combo("setText",initData.mzString);
                $('#hyzkfm').textbox('setValue',initData.hyzk).combobox('setText',initData.hyzkString);
                $('#hjdfm').textbox('setValue',initData.hjd).combobox('setText',initData.hjdString);
                $('#sffm').textbox('setValue',initData.sf).combobox('setText',initData.sfString);
                $('#zzmmfm').textbox('setValue',initData.zzmm).combobox('setText',initData.zzmmString);
                $('#tssffm').textbox('setValue',initData.tssf).combobox('setText',initData.tssfString);
                $('#zyfm').textbox('setValue',initData.zy).combobox("setText",initData.zyString);
                $('#sypzfm').combobox('setValue',initData.sypz).combobox("setText",initData.sypzString);
                $('#rsxzfm').textbox('setValue',initData.rsxz).combobox("setText",initData.rsxzString);
                $('#jgfm').textbox('setValue',initData.jg).combobox("setText",initData.jgString);
                $('#gjfm').textbox('setValue',initData.gj).combobox("setText",initData.gjString);
                $('#whcdfm').textbox('setValue',initData.whcd).combobox("setText",initData.whcdString);
                $('#ayfm').textbox('setValue',initData.ay).combobox("setText",initData.ayString);
                $('#dwlxfm').textbox('setValue',initData.dwlx).combobox("setText",initData.dwlxString);
                $('#rsxzfm').textbox('setValue',initData.rsxz).combobox("setText",initData.rsxzString);
                $('#xzdfm').textbox('setValue',initData.xzd).combobox("setText",initData.xzdString);
                $('#jyaqfm').text(initData.jyaq);
                $("#jlrqjsfm").datebox("textbox").focus(function(){
                	var ts = $("#jlqx").val();
                	var sj = $("#jlrqfm").val();
                	var js =  getShortDatePlus(sj,ts);
                	$("#jlrqjsfm").datebox("setValue",js);
                }); 
            },100);


            $('#centerPhoto').change(function(){
               var  str=$(this).val();
               fileList.centerPhoto=str;
               console.log("1"+str);
            })
            $('#leftPhoto').change(function(){
                var  str=$(this).val();
                fileList.leftPhoto=str;
                console.log("2"+str);
            })
            $('#rightPhoto').change(function(){
                var  str=$(this).val();
                fileList.rightPhoto=str;
                console.log("3"+str);
            })
            

        };

        
        
        var save = function(){
            var url = "/jbxxRsdj/saveForRsdj";
            var $form = $(".awd-jbxx-form");
            var $forms = $(".awd-ajxx-form");
            if (!$form.form('validate')||!$forms.form('validate')) {
                $.messager.alert("提示", '必填项不能为空！');
                return;
            }
            console.log("-------------=="+JSON.stringify(fileList));
            var filelsitJsonStr=JSON.stringify(fileList);
            // var data = $form.serialize();
            // console.log('form data -> ',data);
           // var jbxxData = $form.serializeObject();
            // var formData = new FormData();
            //     formData.append("xm", jbxxData.xm);
            //     formData.append("xb", jbxxData.xb);
            //     formData.append("jsh", jbxxData.jsh);
            //     formData.append("rsxz", jbxxData.rsxz);
            //     formData.append("dah", jbxxData.dah);
            //     formData.append("leftPhoto", $("#leftPhoto")[0].files[0]);
            //     formData.append("rightPhoto", $("#rightPhoto")[0].files[0]);
            //     formData.append("centerPhoto", $("#centerPhoto")[0].files[0]);
            var jbxxData = JSON.stringify($("#jbxx").serializeObject());
            var ajxxData = JSON.stringify($("#ajxx").serializeObject());
            console.log(jbxxData+"++++++++++"+ajxxData+"----------");
            var loadingIndex = layer.load();
            $.ajax({
                type : "POST",  //提交方式
                url : url,
                data : {jbxxDate:jbxxData,ajxxDate:ajxxData,filelsitJsonStr:filelsitJsonStr,photosid:photosid},//数据，这里使用的是Json格式进行传输
                // cache: false,
                // processData: false,
                // contentType: false,
                success : function(result) {
                    layer.closeAll();
                    if (result.success) {
                        _callback && _callback();
                        $.messager.alert("确定","保存成功","info");
                    }else{
                        $.messager.alert("确定","保存失败","warn");
                    }
                },
                complete:function(){
                    layer.close(loadingIndex);
                }
            });
        };
        
        //照片查询
        var photoShwo = function(rybh){
        	$.ajax({
        		type: "POST",  
        		url: "/jls_photos/photosList",  
        		data: {
        			"rybh":rybh,
        		},
        		success: function (result) {
        			var data = result.rows;
        			console.log(result.total);
        			if (result.total != 0) {
        				for(var i = 0;i<result.total;i++){
        					console.log(data[i].photourl);
        					if(data[i].type=="1"&&data[i].photourl!=null&&data[i].photourl!=""){
        						fileList.centerPhoto=data[i].photourl
        						$("#centerPhotoImage").attr("src",data[i].photourl);
        					}
        					if(data[i].type=="2"&&data[i].photourl!=null&&data[i].photourl!=""){
        						fileList.leftPhoto=data[i].photourl
        						console.log(data[i].photourl);
        						$("#leftPhotoImage").attr("src",data[i].photourl);
        					}
        					if(data[i].type=="3"&&data[i].photourl!=null&&data[i].photourl!=""){
        						fileList.rightPhoto=data[i].photourl
        						$("#rightPhotoImage").attr("src",data[i].photourl);
        					}
        				    photosid+=data[i].id+",";
        				}
        				if (photosid.length > 0) {
    				    	photosid = photosid.substr(0, photosid.length - 1);
    				     }
    				    console.log(photosid);
        			}
        		} 
        	});
        }
        var bindAction = function(){
            //保存按钮事件
            $(document).on('click','.save-button',function () {
                save();
            });
            //点击关闭按钮
            $(document).on('click','.close-button',function(){
                layer.close(layerIndex);
                layerIndex = null;
            });
            //修正layer 最大化，解决办法..
            $(window).resize(function(){
                layerIndex && layer.full(layerIndex);
                parseEasyUIElement();//TODO::后续优化
            })
        };

        (function(){
            var componts = require("../../common/componts");
            componts.initSelectPage(undefined);
            componts.initSelect(undefined,undefined,undefined);
            bindAction();
        })()

        return{
            show:_show
        };
    });